﻿using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
using System.Text;
using static System.Net.Mime.MediaTypeNames;

namespace Test
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("按任意键继续");
            Console.ReadKey();

            const string webApiAddr = "http://127.0.0.1:8912"; //webapi的地址，由于网关具有webapi的所有功能，所以这里可以用网关的地址当webapi用
            long productId = 0;
            var userCount = 100;//用户数量
            string[] tokens = new string[userCount];
            int[] indexes = new int[userCount];
            for(int i = 0; i < indexes.Length; i++)
            {
                indexes[i] = i;
            }

            var services = new ServiceCollection();
            services.AddHttpClient();
            var serviceProvider = services.BuildServiceProvider();

            var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

         
            //初始化数据
            if (true)
            {
                Console.WriteLine("初始化数据...");
                var httpClient = httpClientFactory.CreateClient();
               

                StringContent stringContent = new StringContent($"[{userCount}]" , Encoding.UTF8, "application/json");

                var sw = Stopwatch.StartNew();
                var ret = await httpClient.PostAsync($"{webApiAddr}/BusinessService/InitDatas" , stringContent);
                sw.Stop();
                var es = sw.ElapsedMilliseconds;

                var text = await ret.Content.ReadAsStringAsync();
                if(ret.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine($"初始化完毕，产品id：{text} 耗时：{es}毫秒  用户数：{userCount}");
                    productId = long.Parse(text);
                }
                else
                {
                    Console.WriteLine("初始化异常，" + text);
                }
            }

            //登录
            if (true)
            {
                Console.WriteLine("登录...");
                long min = long.MaxValue, max = long.MinValue;
                await Parallel.ForEachAsync(indexes, CancellationToken.None, async (index , cancellationToken) => {
                    
                    var httpClient = httpClientFactory.CreateClient();
                    var userid = index + 1;

                    StringContent stringContent = new StringContent($"[{userid}]", Encoding.UTF8, "application/json");

                    var sw = Stopwatch.StartNew();

                    var ret = await httpClient.PostAsync($"{webApiAddr}/BusinessService/Login", stringContent);
                    sw.Stop();
                    var es = sw.ElapsedMilliseconds;
                    lock (indexes)
                    {
                        if (es < min)
                            min = es;
                        if (es > max)
                            max = es;
                    }

                    var text = await ret.Content.ReadAsStringAsync();
                    if (ret.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        tokens[index] = text;
                    }
                    else
                    {
                        Console.WriteLine($"用户{userid}登录异常，{text}");
                    }
                });

                Console.WriteLine($"用户登录完毕，最小耗时：{min}毫秒  最大耗时{max}毫秒");
            }

            //下单
            if (true)
            {
                Console.WriteLine("开始下单+支付...");
                long min = long.MaxValue, max = long.MinValue;
                await Parallel.ForEachAsync(indexes, CancellationToken.None, async (index, cancellationToken) => {

                    var httpClient = httpClientFactory.CreateClient();
                    var userid = index + 1;
                    var token = tokens[index];
                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(token);

                    StringContent stringContent = new StringContent($"[{productId} , 1]", Encoding.UTF8, "application/json");

                    var sw = Stopwatch.StartNew();

                    var ret = await httpClient.PostAsync($"{webApiAddr}/BusinessService/Buy", stringContent);
                    sw.Stop();
                    var es = sw.ElapsedMilliseconds;
                    

                    var text = await ret.Content.ReadAsStringAsync();
                    if (ret.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        Console.WriteLine($"用户{userid}下单完毕，耗时{es}毫秒");
                    }
                    else
                    {
                        Console.WriteLine($"用户{userid}下单异常，{text}");
                    }

                    lock (indexes)
                    {
                        if (es < min)
                            min = es;
                        if (es > max)
                            max = es;
                    }
                });

                Console.WriteLine($"用户下单完毕，最小耗时：{min}毫秒  最大耗时{max}毫秒");
            }
            Console.ReadLine();
        }
    }
}
